<?php

/* If no headers was sent: main call */
if (!headers_sent())
{
    $excel = True;

    require('database.php');
    require('auth.php');
    require('core.php');

    /* Get employee data */
    include('employee_get_data.php');

    // Define file type
    header("Content-type: application/vnd.ms-excel");

    // Define file name and to be downloaded
    header("Content-Disposition: attachment; filename=\"{$contato_employee['name']}.xls"); 
}

/* Gets time period */
$from = (@$_GET['from']? strtotime($_GET['from']) : inicio_ultima_quinzena());
$to = (@$_GET['to']? strtotime($_GET['to']) : fim_ultima_quinzena());

if ($to)
	$to = min($to, $_SERVER['REQUEST_TIME']);

// Realiza consulta
$resultado = query_bd("SELECT *, clocks.labor, clocks.labor_expense FROM clocks, reports WHERE " .
	"clocks.employee_id ='{$employee['id']}' AND " .
	"clocks.report_id = reports.id AND reports.state = " . ACCEPTED .
	(@$_GET['period'] != 0? " AND reports.period={$_GET['period']}" : "") .
	(@$_GET['location'] != 0? " AND reports.special_event = False AND reports.location_event_id ='{$_GET['location']}'" : "") .
	($from? " AND UNIX_TIMESTAMP(reports.reportdate) >= {$from}" : "") .
	($to? " AND UNIX_TIMESTAMP(reports.reportdate) <= {$to}" : "")  .
	" ORDER BY reports.reportdate, reports.period, clocks.intime");

// Renderiza tabela com os dados
echo "<table id='employee'>";

if (!isset($excel))
    echo "<caption><em>{$contato_employee['name']}'s working sheet",
    ($from? " from " . date("M j Y", $from) : ""),
    ($to? " until " . date("M j Y", $to) : ""),
     ", " . mysql_affected_rows() . " reports",
    (@$_GET['location']? " subjected to location {$location_name}" : ""),
    "</em></caption><tr>";

unset($contato_employee);

if (nivelAutenticado() >= 3 && !isset($excel))
	echo "<th>";

echo "<th>Date<th>Location/Event<th>Period<th>In<th>Out<th>Labor<th>Labor expense(+tip)";

$LABOR = '00:00:00';
$LABOR_EXP = 0;

while ($dados = mysql_fetch_array($resultado))
{
	// Imprime cada linha da tabela
	echo "<tr>";
	if (nivelAutenticado() >= 3 && !isset($excel))
		echo "<td><a href='"  . dirname($_SERVER['HTTP_REFERER']) . "/report.php?id=", $dados['report_id'], "'>",
        "<img src='"  . dirname($_SERVER['HTTP_REFERER']) . "/img/report.png' alt='View report details'></a>";
	echo "<td>", date("D, M d Y", strtotime($dados['reportdate']));

	// Busca nome da locacao ou evento
	if ($dados['special_event'])
	{
		$evento = query_fetch("SELECT * FROM events WHERE id={$dados['location_event_id']}");

		echo "<td>", (nivelAutenticado() >= 3? 
            "<a href='"  . dirname($_SERVER['HTTP_REFERER']) . "/report.php?id={$dados['report_id']}'>" : ""),
		$evento['name'],
		(nivelAutenticado() >= 3? "</a>" : "");
	}
	else
	{
		$locacao = query_fetch("SELECT contacts.name, locations.operating FROM locations, contacts" .
			" WHERE locations.id={$dados['location_event_id']} AND contacts.id = locations.locationcontact");

		echo "<td>" . (nivelAutenticado() >= 3? 
            "<a href='"  . dirname($_SERVER['HTTP_REFERER']) . "/location.php?id={$dados['location_event_id']}'>" : ""),
		$locacao['name'] . ($locacao['operating']? "" : "(not operating)"),
		(nivelAutenticado() >= 3? "</a>" : "");
	}

	//Periodo
	echo "<td>{$PERIOD[$dados['period']]}";

	// Soma com o tempo total
	$result = query_fetch("SELECT TIMEDIFF('{$dados['labor']}', '-{$LABOR}') AS sum");
	$LABOR = $result['sum'];

	// Soma pagamento
	$LABOR_EXP += $dados['labor_expense'];

	echo "<td>", formatTime($dados['intime']), "<td>",
	formatTime($dados['outtime']), "<td>", formatTime($dados['labor']), "<td>",
	show_money(-$dados['labor_expense']);

	unset($dados);
}
echo "<tr>", (nivelAutenticado() >= 3 && !isset($excel)? "<th>" : ""), "<th><th><th><th><th><th>",
	($LABOR != "00:00:00"? formatTime($LABOR) : "-"), "<th>", show_money(-$LABOR_EXP);
echo "</table>";

?>
